package com.example.week2_try2;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.icu.text.SimpleDateFormat;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


public class RateList extends AppCompatActivity implements Runnable,AdapterView.OnItemLongClickListener,AdapterView.OnItemClickListener {
    public static final String TAG= "RateList";
    //private ArrayList<HashMap<String,String>> listItems;
    private SimpleAdapter listItemAdaptor;//适配器
    Handler handler;
    ListView mylist2;
    MyAdapter myAdapter;
    private String logDate = "";
    private final String DATE_SP_KEY = "lastRateDateStr";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rate_list);

//        SharedPreferences sp = getSharedPreferences("myrate", Context.MODE_PRIVATE);
//        logDate = sp.getString(DATE_SP_KEY, "");
//        Log.i("List","lastRateDateStr=" + logDate);
        //定义新数据格式
        Log.i(TAG, "onCreate: =");
//        for(int i = 0;i<10;i++){
//            HashMap<String,String> map = new HashMap<String,String>();//map一定要在循环里创建，在外面的话就是同一个map不停的放进list
//            map.put("ItemTitle","Rate: = "+i);//标题文字
//            map.put("ItemDetail","detail: = "+i);//详情描述
//            listItems.add(map);
//        }


        ProgressBar bar=findViewById(R.id.my_progressbar);
        mylist2 = findViewById(R.id.mylist2);
        mylist2.setOnItemClickListener(this);//绑定事件处理
        mylist2.setOnItemLongClickListener(this);
//        Thread thread=new Thread(this);//要放当前对象
//        thread.start();//自动调用run方法
        handler=new Handler(Looper.myLooper()){//
            @Override
            public void handleMessage(@NonNull Message msg) {
                Log.d(TAG, "handleMessage: 收到消息");
                if(msg.what==9){
                    //提取数据
//                    listItems = (ArrayList<HashMap<String,String>>) msg.obj;
                    ArrayList<Item> listItems = (ArrayList<Item>) msg.obj;
                    //SimpleAdapter
//                    listItemAdaptor = new SimpleAdapter(RateList.this,listItems,
//                            R.layout.list_item,
//                            new String[]{"ItemTitle","ItemDetail"},
//                            new int[] {R.id.itemtitle,R.id.itemDetail});
//                    Log.i(TAG, "onCreate: listItems"+listItems);
//                    mylist2 = findViewById(R.id.mylist2);
//                    mylist2.setAdapter(listItemAdaptor);

                    //自定义Adapter
                    myAdapter = new MyAdapter(RateList.this,R.layout.list_item,listItems);
                    mylist2.setAdapter(myAdapter);
                    mylist2.setEmptyView(findViewById(R.id.nodata));

                    //切换显示状态
                    bar.setVisibility(View.GONE);
                    mylist2.setVisibility(View.VISIBLE);

                }
                if(msg.what==5){
                    ArrayList<RateItem> rateList = new ArrayList<RateItem>();
                    Log.i(TAG, "handleMessage: 数据库");
                    MyAdapter2 myAdapter2 = new MyAdapter2(RateList.this,R.layout.list_item,rateList);
                    mylist2.setAdapter(myAdapter2);
                    mylist2.setEmptyView(findViewById(R.id.nodata));

                    //切换显示状态
                    bar.setVisibility(View.GONE);
                    mylist2.setVisibility(View.VISIBLE);

                }
                super.handleMessage(msg);
            }
        };

        //用其他方法
//        RateTask myTask = new RateTask();
        RateItemTask myTask = new RateItemTask();
        myTask.setHandler(handler);    //不调用该方法会显示空指针异常
        Thread thread = new Thread(myTask);
        thread.start();

//        Log.i(TAG, "onCreate: listItems"+listItems);
        //生成适配器的Item和动态数组对应的元素





    }





    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
        Object itemAtPosition = mylist2.getItemAtPosition(position);
//        HashMap<String,String> map = (HashMap<String, String>) itemAtPosition;
        Item item = (Item) itemAtPosition;
//        String titleStr = map.get("ItemTitle");
//        String detailStr = map.get("ItemDetail");
        String titleStr = item.getCname();
        String detailStr = item.getCval();
        Log.i(TAG, "onItemClick: titleStr="+titleStr);
        Log.i(TAG, "onItemClick: detailStr="+detailStr);

        Intent first = new Intent(this, RateCalcActivity.class);//this当前activity对象
        first.putExtra("titleStr", titleStr);
        first.putExtra("detailStr", detailStr);

        //startActivity(first);
        startActivity(first);
        //从控件获得
//        TextView title = (TextView) view.findViewById(R.id.itemtitle);
//        TextView detail = (TextView) view.findViewById(R.id.itemDetail);
//        String title2=String.valueOf(title.getText());
//        String detail2=String.valueOf(detail.getText());
//        Log.i(TAG, "onItemClick: title2="+title2);
//        Log.i(TAG, "onItemClick: detail2="+detail2);
    }


    @Override
    public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) {
        //布尔可避免同时触发单击事件
        Log.i(TAG, "onItemLongClick: 长按处理");
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示")
                .setMessage("请确认是否需要删除")
                .setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Log.i(TAG, "onClick: 对话框事件处理");
                        myAdapter.remove(mylist2.getItemAtPosition(position));
                    }
                }).setNegativeButton("否",null);
        builder.create().show();

        return true;//避免同时出发单击事件处理函数

    }

    @Override
    public void run() {
        Log.i("List","run...");
        //List<String> retList = new ArrayList<String>();
        List<RateItem> retList=new ArrayList<RateItem>();

        Message msg = handler.obtainMessage();
        String curDateStr = (new SimpleDateFormat("yyyy-MM-dd")).format(new Date());
        Log.i("run","curDateStr:" + curDateStr + " logDate:" + logDate);
        if(curDateStr.equals(logDate)){
            //如果相等，则不从网络中获取数据
            Log.i("run","日期相等，从数据库中获取数据");
            DBManager dbManager = new DBManager(RateList.this);
            for(RateItem rateItem : dbManager.listAll()){
                //retList.add(rateItem.getCurName() + "=>" + rateItem.getCurRate());
                RateItem item = new RateItem(rateItem.getCurName(),rateItem.getCurRate());
                retList.add(item);
            }
        }else{
            Log.i("run","日期相等，从网络中获取在线数据");
            //获取网络数据
            try {
                Document doc = null;
                doc = Jsoup.connect("https://www.boc.cn/sourcedb/whpj/").get();
                Log.i(TAG, "run: "+doc.title());
                Elements tables=doc.getElementsByTag("table");
                //Log.i(TAG, "run: tables="+tables);
                Element secondTable=tables.get(1);//单位元素--获取第二个table
                Log.i(TAG, "run: table="+secondTable);
                //通过行获取数据
                Elements trs=secondTable.getElementsByTag("tr");
                trs.remove(0);
                for(Element tr:trs){
                    Log.i(TAG, "run: tr="+tr);
                    //从行中获得td元素
                    Elements tds=tr.getElementsByTag("td");
                    //获取第一列
                    Element td1=tds.get(0);
                    Element td2=tds.get(4);
                    Log.i(TAG, "run: td1="+td1.text()+"\n run: td2="+td2.text());
                    if(!(td2.text().equals(""))){
                        HashMap<String,String> map = new HashMap<String,String>();//map一定要在循环里创建，在外面的话就是同一个map不停的放进list

                        float rate = 100f/Float.parseFloat(td2.text());//计算汇率
                        RateItem item = new RateItem(td1.text(),String.valueOf(rate));
                        retList.add(item);
//                    list2.add(td1.text()+"------>"+String.valueOf(rate));
//                    map.put("ItemTitle",td1.text());//标题文字
//                    map.put("ItemDetail",String.valueOf(rate));//详情描述
                        //listItems.add(map);
                    }
                    else{
                        HashMap<String,String> map = new HashMap<String,String>();//map一定要在循环里创建，在外面的话就是同一个map不停的放进list
                        RateItem item = new RateItem(td1.text(),td2.text());
                        retList.add(item);
//                    map.put("ItemTitle",td1.text());//标题文字
//                    map.put("ItemDetail",td2.text());//详情描述
                        //listItems.add(map);
//                    list2.add(td1.text()+"------>"+td2.text());
                    }
                }
                Message msg2=handler.obtainMessage(5,retList);//括号内可写what
                handler.sendMessage(msg2);
            } catch (IOException e) {
                e.printStackTrace();
            }

            //更新记录日期
            SharedPreferences sp = getSharedPreferences("myrate", Context.MODE_PRIVATE);
            SharedPreferences.Editor edit = sp.edit();
            edit.putString(DATE_SP_KEY, curDateStr);
            edit.commit();
            Log.i("run","更新日期结束：" + curDateStr);
        }

        msg.obj = retList;
        msg.what = 5;
        handler.sendMessage(msg);
    }
}